const fs = require("fs");
const path = require("path");
const url = require("url");

/**
 * 使用同步方法读取json文件
 * @param {*} extname
 * @returns
 */
const getFileMineSync = function (extname) {
  let data = fs.readFileSync("./data/mime.json"); // 同步方法
  let mineObj = JSON.parse(data.toString());
  return mineObj[extname]
}

exports.static = function (req, res, staticPath) {
  // 1. 获取地址
  let pathname = url.parse(req.url).pathname;
  pathname = pathname == '/' ? '/index.html' : pathname;
  let extname = path.extname(pathname); // 获取后缀名

  if (pathname !== "/favicon.ico") {
    try {
      // 通过 fs 模块读取文件
      let data = fs.readFileSync('./' + staticPath + pathname);
      if (data) {
        const responseHeader = getFileMineSync(extname);
        res.writeHead(200, { 'Content-Type': `${responseHeader};charset='utf-8'` });
        res.end(data);
      }
    } catch (error) {}
  }
}